package com.klun.project.dal.common.interceptor;


import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.data.domain.Pageable;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class PagingInterceptor implements MethodInterceptor {
	private static final String COUNT_METHOD_SUFFIX = "Count";

	public PagingInterceptor() {
	}

	public Object invoke(MethodInvocation invocation) throws Throwable {
		try {
			Object[] args = invocation.getArguments();
			if (args != null && args.length > 0 && args[0] instanceof Pageable) {
				String methodName = invocation.getMethod().getName();
				long total = 0L;

				try {
					Method method = invocation.getThis().getClass().getMethod(methodName + "Count", invocation.getMethod().getParameterTypes());
					total = (Long)method.invoke(invocation.getThis(), args);
				} catch (Exception var7) {
				}

				Object result = invocation.proceed();
				if (result instanceof List) {
					return 0L == total ? new PagingArrayList((ArrayList)result, (Pageable)args[0], (long)((ArrayList)result).size()) : new PagingArrayList((ArrayList)result, (Pageable)args[0], total);
				} else {
					return result;
				}
			} else {
				Object result = invocation.proceed();
				return result;
			}
		} catch (Throwable var8) {
			return invocation.proceed();
		}
	}
}
